package com.doublefish.doublefishrobot.ui.home;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.bean.DeviceBean;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.ble.DFBleManager;
import com.doublefish.doublefishrobot.utils.ble.DFS6ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.DFS8ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.bean.BleOffsetBean;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;
import com.doublefish.doublefishrobot.utils.ble.bean.OnBleResponseHandler;
import com.doublefish.doublefishrobot.widget.LoadingDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/11/7 16:12
 */
public class DeviceCheckActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView titleTv;

    @BindView(R.id.tv_right)
    TextView rightTv;

    @BindView(R.id.tv_ver)
    TextView verTv;
    @BindView(R.id.tv_hor)
    TextView horTv;
    @BindView(R.id.tv_rotation)
    TextView rotationTv;

    private DeviceBean deviceBean;
    private BleOffsetBean offsetBean;

    private int stepSize = 1;  //每次变化的步数

    private boolean didConnected = false;   //进入这个页面时，是否是连接状态

    public static Intent makeIntent(Activity activity, DeviceBean deviceBean) {
        AppCacheUtil.getInstance().setIntentBean(deviceBean);

        Intent intent = new Intent(activity, DeviceCheckActivity.class);
        return intent;
    }

    @Override
    protected void onDestroy() {
        if (didConnected) {
            super.onDestroy();
            return;
        }
        DFBleManager.getInstance().disConnect();
        super.onDestroy();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_check;
    }

    @Override
    protected void initView() {
        titleTv.setText(R.string.init_check);

        ViewGroup.LayoutParams layoutParams = rightTv.getLayoutParams();
        layoutParams.width = dip2px(30);
        layoutParams.height = dip2px(30);
        rightTv.setLayoutParams(layoutParams);
        rightTv.setBackground(getResources().getDrawable(R.mipmap.bangzhu));

        rightTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toCheckHelpActivty();
            }
        });
    }

    @Override
    protected void initData() {
        deviceBean = AppCacheUtil.getInstance().getIntentBean();
        if (deviceBean.getDeviceType() == ModeConstant.DeviceTypeS8) {
            stepSize = 10;  //超6每次加减1  超8 超8每次加减10
        }
        //检查蓝牙连接状态
        checkConnectState();
    }

    @Override
    protected void initListener() {

    }

    @OnClick(R.id.ll_back)
    public void onBackBtnClick() {
        finish();
    }

    @OnClick({R.id.fl_up, R.id.fl_down, R.id.fl_left, R.id.fl_right, R.id.iv_left, R.id.iv_right})
    public void onValueBtnClick(View view) {
        if (offsetBean == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.fl_up: {
                offsetBean.setElevationOffset(offsetBean.getElevationOffset() - stepSize);
            }
            break;
            case R.id.fl_down: {
                offsetBean.setElevationOffset(offsetBean.getElevationOffset() + stepSize);
            }
            break;
            case R.id.fl_left: {
                offsetBean.setLandingPointOffset(offsetBean.getLandingPointOffset() - stepSize);
            }
            break;
            case R.id.fl_right: {
                offsetBean.setLandingPointOffset(offsetBean.getLandingPointOffset() + stepSize);
            }
            break;
            case R.id.iv_left: {
                offsetBean.setSideSpinOffset(offsetBean.getSideSpinOffset() - stepSize);
            }
            break;
            case R.id.iv_right: {
                offsetBean.setSideSpinOffset(offsetBean.getSideSpinOffset() + stepSize);
            }
            break;
        }
        refreshView();
        setMachineOffset();
    }

    @OnClick(R.id.tv_test)
    public void onTestBtnClick(View view) {
        if (offsetBean == null) {
            return;
        }
        if (DFBleManager.getInstance().curDeviceIsProtocolTypeS8()) {
            //发一个最基础的球
//            String script = "0,1,#0,20,#0,40,#0,25,#0,25,#0,19,#0,90,#\n";
            //双鱼要求，中间校准位置从08格改为01格，内部校准点还是08格，测试发球时radian参数加5，瞄准01格发球  radian = 19 + 5 = 24
            String script = "0,1,#0,20,#0,40,#0,25,#0,25,#0,24,#0,90,#\n";
            DFS8ProtocolManager.getInstance().testBall(script);
        } else if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
            //发一个最基础的球
//            String script = "0,1,#0,40,#0,11,#0,29,#0,9,#0,20,#0,8,#\n";
            String script = "0,1,#0,40,#0,10,#0,20,#0,9,#0,17,#0,8,#\n";
            DFS8ProtocolManager.getInstance().testBall(script);
        }
    }

    @OnClick(R.id.tv_save)
    public void onSaveBtnClick(View view) {
        if (offsetBean == null) {
            return;
        }
        saveMachineOffset();
    }

    private void checkConnectState() {
        if (DFBleManager.getInstance().isDidConnectBlueTooth()) {
            didConnected = true;
            //已连接
            getMachineOffset();
            return;
        }

        //先连接
        showLoadingDialog(0);
        connectBle();
    }

    private void connectBle() {
        DFBleManager.getInstance().setOnBleManagerListner(new DFBleManager.OnBleManagerListner() {
            @Override
            public void onScanResult(List<DeviceBean> deviceBeanList) {

            }

            @Override
            public void onConnectBle(boolean success, DeviceBean deviceBean) {
                if (success) {
                    showToast(getString(R.string.success_ble));
                    //连接发球机
                    connectMachine();
                } else {
                    showToast(getString(R.string.fail_ble));
                }
            }

            @Override
            public void onDisConnectBle() {

            }
        });
        DFBleManager.getInstance().connectBt(deviceBean.getTid(), deviceBean.getMac(), deviceBean.getName(), deviceBean.getDeviceType());
    }

    private void connectMachine() {
        if (DFBleManager.getInstance().curDeviceIsProtocolTypeS8()) {
            DFS8ProtocolManager.getInstance().connectMachine(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        getMachineOffset();
                    } else {
                        showToast(getString(R.string.fail_get_offset_tip));
                    }
                    return false;
                }
            });
        } else if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
            DFS6ProtocolManager.getInstance().connectMachine(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        getMachineOffset();
                    } else {
                        showToast(getString(R.string.fail_get_offset_tip));
                    }
                    return false;
                }
            });
        }
    }

    private void getMachineOffset() {
        showLoadingDialog(1);
        if (DFBleManager.getInstance().curDeviceIsProtocolTypeS8()) {
            showToast(getString(R.string.reading_offset_tips));
            DFS8ProtocolManager.getInstance().getMachineOffset(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        showToast(getString(R.string.success_get_offset_tip));
                        offsetBean = (BleOffsetBean) res;
                        //刷新页面数据
                        refreshView();

                    } else {
                        showToast(getString(R.string.fail_get_offset_tip));
                    }
                    return false;
                }
            });
        }
        else if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
            showToast(getString(R.string.reading_offset_tips));
            DFS6ProtocolManager.getInstance().getMachineOffset(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        showToast(getString(R.string.success_get_offset_tip));
                        offsetBean = (BleOffsetBean) res;
                        //刷新页面数据
                        hideLoadingDialog();
                        refreshView();

                    } else {
                        showToast(getString(R.string.fail_get_offset_tip));
                    }
                    return false;
                }
            });
        }
    }

    private void refreshView() {
        if (offsetBean == null) {
            return;
        }
        try {
            verTv.setText(getString(R.string.up_down_) + offsetBean.getElevationOffset());
            horTv.setText(getString(R.string.left_right_) + offsetBean.getLandingPointOffset());
            rotationTv.setText(getString(R.string.sidespin_) + offsetBean.getSideSpinOffset());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setMachineOffset() {
        if (offsetBean == null) {
            return;
        }
        if (DFBleManager.getInstance().curDeviceIsProtocolTypeS8()) {
            DFS8ProtocolManager.getInstance().setMachineOffset(offsetBean.getLandingPointOffset(), offsetBean.getElevationOffset(), offsetBean.getSideSpinOffset(), null);
        } else if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
            DFS6ProtocolManager.getInstance().setMachineOffset(offsetBean.getLandingPointOffset(), offsetBean.getElevationOffset(), offsetBean.getSideSpinOffset(), null);
        }
    }

    private void saveMachineOffset() {
        if (offsetBean == null) {
            return;
        }
        if (DFBleManager.getInstance().curDeviceIsProtocolTypeS8()) {
            DFS8ProtocolManager.getInstance().saveMachineOffset(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    String msg = success ? getString(R.string.success_save) : getString(R.string.fail_save);
                    showToast(msg);
                    return false;
                }
            });
        } else if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
            DFS6ProtocolManager.getInstance().saveMachineOffset(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    String msg = success ? getString(R.string.success_save) : getString(R.string.fail_save);
                    showToast(msg);
                    return false;
                }
            });
        }
    }

    private LoadingDialog loadingDialog = null;
    private void showLoadingDialog(int type) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
        if (type == 0) {
            loadingDialog.setMsg(getString(R.string.ble_connecting_tips));
        } else {
            loadingDialog.setMsg(getString(R.string.reading_offset_tips));
        }

        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
            hideLoadingDialogDelay();
        }
    }

    private void hideLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    private void hideLoadingDialogDelay() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
               hideLoadingDialog();
            }
        }, 5000);
    }

    private void toCheckHelpActivty() {
        Intent intent = new Intent(this, DeviceCheckHelpActivity.class);
        startActivity(intent);
    }

    private int dip2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
